// Copyright (C) 2009 Jesse Jones
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

using MmmDoc;
using System;
using System.Collections.Generic;

namespace MmmDoc.Database
{
	/// <summary>Name of a program element, e.g. a type or member.</summary>
	/// <remarks>Corresponds to cref attributes in the XML.</remarks>
	internal sealed class CodeReference
	{
		public CodeReference(string name)
		{
			Contract.Requires(name.Length > 2, name + " is too short");
			Contract.Requires(name[1] == ':', name + " is missing a colon");
			
			Prefix = name[0];
			XmlName = name.Substring(2);
			
			ms_refs.Add(this);
		}
		
		/// <summary>Full type or member name.</summary>
		/// <remarks>This does not include the "T:" or "M:" prefix from the XML.</remarks>
		public string XmlName {get; private set;}
		
		/// <summary>Resolved code element.</summary>
		/// <returns>May be null.</returns>
		public CodeElement Element {get; private set;}
		
		internal static void Resolve(Document doc)
		{
			foreach (CodeReference cr in ms_refs)
			{
				cr.DoResolve(doc);
			}
		}
		
		internal char Prefix {get; private set;}
		
		#region Private Methods
		private void DoResolve(Document doc)
		{
			if (Prefix == 'T')
			{
				DoResolveType(doc);
			}
			else
			{
				DoResolveMember(doc);
			}
		}
		
		private void DoResolveType(Document doc)
		{
			bool matchedNamespace = false;
			bool hasNamespace = XmlName.Contains(".");
			
			for (int i = 0; i < doc.Types.Length && Element == null; ++i)
			{
				TypeDef type = doc.Types[i];
				
				if (!matchedNamespace)
				{
					if (hasNamespace && type.Namespace.Length > 0)
					{
						if (XmlName.StartsWith(type.Namespace))
							matchedNamespace = true;
					}
					else if (!hasNamespace && type.Namespace.Length == 0)
					{
						matchedNamespace = true;
					}
				}
				
				if (XmlName == type.GetXmlName())
					Element = type;
			}
			
			if (Element == null)
				if (matchedNamespace)
					Console.Error.WriteLine("Couldn't resolve {0}:{1}", Prefix, XmlName);
				else if (Settings.Verbosity >= 1)
					Console.WriteLine("Couldn't resolve {0}:{1}", Prefix, XmlName);	// this is most likely an external type (like a reference to a system exception)
		}
		
		// It'd be more efficient to break the name apart, find the matching type,
		// and then the matching method but it's much easier to build a new name
		// than to parse the name using the xml.
		private void DoResolveMember(Document doc)
		{
			string name = Prefix + ":" + XmlName;
			
			for (int i = 0; i < doc.Types.Length && Element == null; ++i)
			{
				TypeDef type = doc.Types[i];
				
				if (XmlName.StartsWith(type.GetXmlName()))
				{
					for (int j = 0; j < type.Members.Length && Element == null; ++j)
					{
						Member member = type.Members[j];
						
						if (name == member.GetXmlName(type))
							Element = member;
					}
				}
			}
			
			if (Element == null)
				Console.Error.WriteLine("Couldn't resolve {0}:{1}", Prefix, XmlName);
		}
		#endregion
		
		#region Fields
		private static List<CodeReference> ms_refs = new List<CodeReference>();
		#endregion
	}
}
